﻿/*
 * Copyright (C) 2012, Jesus Requejo <jesus.requejo@gmail.com> 
 * Licensed under Microsoft Public License (Ms-PL)
 * http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/

namespace LoaderServiceManager {

   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Windows.Forms;
   using Infrastructure;
   
   public partial class PredefinedAppsCheckList : Form {

      private IList<ApplicationEntry> AppList;
      public IList<ApplicationEntry> SelectedApps = new List<ApplicationEntry>();

      protected PredefinedAppsCheckList() {
         InitializeComponent();
      }

      public PredefinedAppsCheckList(IList<ApplicationEntry> appList)
         : this() {
         InitializeListView(appList);
      }

      private void InitializeListView(IList<ApplicationEntry> appList) {
         AppList = appList.OrderBy(app => app.Name).ToList();
         int autoSize = -2;
         appListView.Columns.Add("", 20 , HorizontalAlignment.Left);
         appListView.Columns.Add("Name", autoSize, HorizontalAlignment.Left);
         appListView.Columns.Add("Path", autoSize, HorizontalAlignment.Left);
         var appsArray = AppList.Select(app => {
            var item = new ListViewItem("");
            item.SubItems.Add(app.Name);
            item.SubItems.Add(app.Path);
            return item;
         }).ToArray();

         appListView.Items.AddRange(appsArray);
         appListView.CheckBoxes = true;
         appListView.View = View.Details;
         appListView.GridLines = true;
         appListView.HeaderStyle = ColumnHeaderStyle.Nonclickable;
         appListView.MultiSelect = false;
         appListView.FullRowSelect = true;         
      }
    
      private void okButton_Click(object sender, EventArgs e) {
         var selectedItems = appListView.CheckedItems;
         var apps = selectedItems.
            Cast<ListViewItem>().
            Select(item => {
               var name = item.SubItems[1].Text;
               var path = item.SubItems[2].Text;
               return new ApplicationEntry() { Name = name, Path = path };
            });

         SelectedApps = apps.ToList();
         Close();
      }

      private void cancelButton_Click(object sender, EventArgs e) {
         Close();
      }
   }
}
